﻿using System;
using System.Diagnostics;
using System.Resources;
using CTS.Com.Domain.Model;
using CTS.Com.Domain.Validate.Model;

namespace CTS.Com.Domain.Helper
{
    public static class AppHelper
    {
        public static void LoadValidateRules(Type type, string path)
        {
            var rules = ContextHelper.ValidateRules;
            var stream = type.Assembly.GetManifestResourceStream(path);
            var exRules = XmlHelper.Deserialize<Rules>(stream);
            foreach (var rule in exRules) {
                if (!rules.Contains(rule)) {
                    rules.Add(rule);
                }
            }
            ContextHelper.ValidateRules = rules;
        }

        public static void LoadMessageResources(ResourceManager rm)
        {
            var mrs = ContextHelper.MessageResources;
            if (mrs.Contains(rm)) {
                return;
            }
            mrs.Add(rm);
            ContextHelper.MessageResources = mrs;
        }

        public static void LoadNameResources(ResourceManager rm)
        {
            var mrs = ContextHelper.NameResources;
            if (mrs.Contains(rm)) {
                return;
            }
            mrs.Add(rm);
            ContextHelper.NameResources = mrs;
        }

        public static void LoadFormatResources(ResourceManager rm)
        {
            var mrs = ContextHelper.FormatResources;
            if (mrs.Contains(rm)) {
                return;
            }
            mrs.Add(rm);
            ContextHelper.FormatResources = mrs;
        }

        public static void LoadUserContext(object context)
        {
            var obj = new UserContext();
            DataHelper.CopyObject(context, obj);
            ContextHelper.UserContext = obj;
        }

        public static Type GetCallerType(StackFrame sf)
        {
            return sf.GetMethod().DeclaringType;
        }

        public static string GetResourceByType(Type type, string fileName)
        {
            var nsDom = type.Namespace;
            var nsRes = nsDom.Replace("Domain", "Resources");
            return string.Format("{0}.{1}", nsRes, fileName);
        }
    }
}